<template>
  <div class="content-container">
    <el-breadcrumb separator-class="el-icon-arrow-right" class="pd-total">
      <el-breadcrumb-item :to="{ name: 'project',params: { pn1: this.pn} }">项目管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ name: 'project',params: { pn1: this.pn} }" v-if="!$route.query.isclose">正式项目</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/project', query: { isclose: $route.query.isclose } }" v-else>已关闭项目
      </el-breadcrumb-item>
      <el-breadcrumb-item>进度管理</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card mr">
      <el-row class="subtitle-div" type="flex" justify="space-between">
        <el-col>
          <span class="progress-manager-subtitle">{{ projectName }}</span>
          <el-select v-model="versionId" size="small" placeholder="请选择" class="version-select" @change="changeVersion">
            <el-option v-for="item in verOptions" :key="item.id" :label="item.verNumber" :value="item.id"></el-option>
          </el-select>
          <el-button type="primary" size="small" class="green-btn" @click="managerVersion"
            v-show="authority.canOperateVersion">版本管理</el-button>
        </el-col>
      </el-row>
    </el-card>
    <!-- 整体计划 -->
    <el-card class="box-card mr">
      <el-row type="flex" justify="space-between">
        <el-col :span="4">
          <div class="progress-manager-subtitle">整体计划</div>
        </el-col>
        <el-col :span="20" class="rh">
          <el-button type="primary" size="small" class="new-add-btn green-btn" @click="addPlan('添加计划')"
            v-show="authority.canOperatePlan">添加计划</el-button>
        </el-col>
      </el-row>
      <ProgressTable :tableSetting="totalPlanSetting" @modifyPlan="modifyPlan" :authority="authority"
        @verPlanListData="verPlanListData" />
    </el-card>

    <el-card class="box-card">
      <el-row type="flex" justify="space-between" style="margin-bottom:20px;">
        <el-col :span="4">
          <div class="progress-manager-subtitle">任务端管理</div>
        </el-col>
        <el-col :span="20" class="rh">
          <el-button type="primary" size="small" class="new-add-btn green-btn" @click="newTask('新增任务端')"
            v-if="authority.canOperateTaskPort">新增任务端</el-button>
          <el-button type="primary" size="small" class="new-add-btn blue-btn" @click="managerFunctionList">功能列表
          </el-button>
        </el-col>
      </el-row>

      <ProjectProgress :setting="lineProgress" @modifyTask="modifyTask" :authority="authority"
        :circleProgress="circleProgress" @updateTaskPort="updateTaskPort" />
      <ProjectProgress :setting="circleProgress" />
    </el-card>

    <!-- 测试bug数管理 -->
    <el-card class="box-card mr">
      <el-row type="flex">
        <el-col>
          <div class="progress-manager-subtitle">测试bug数管理</div>
        </el-col>
      </el-row>
      <el-row type="flex" class="mr-bt">
        <el-col>
          <el-table :data="bugNumlist" border :header-cell-style="{ background: '#F9F9F9' }" align="center">
            <el-table-column label="姓名" width="100" align="center" prop="devUserName"></el-table-column>
            <el-table-column prop="bugLevelOne" label="一级Bug数" align="center"></el-table-column>
            <el-table-column prop="bugRuleCount" label="常规Bug" align="center"></el-table-column>
            <el-table-column prop="bugCount" label="Bug总数" align="center"></el-table-column>
            <el-table-column prop="bugLevelOneRate" label="一级Bug率" align="center"></el-table-column>
            <el-table-column prop="bugRate" label="Bug率" align="center"></el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button :disabled="!authority.canSubmitBugs" size="mini" type="success" plain
                  @click="handleAddbug(scope.row, '新增bug')">新增bug</el-button>
                <el-button :disabled="!authority.canSubmitBugs" size="mini" type="primary" plain
                  @click="handleAddbug(scope.row, '减除bug')">减除bug</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-card>

    <!-- 版本总结 -->
    <el-card class="box-card mr">
      <el-row type="flex">
        <el-col>
          <div class="progress-manager-subtitle">版本总结</div>
        </el-col>
      </el-row>
      <el-row type="flex" class="mr-bt" id="summary">
        <el-col>
          <el-upload :headers="headers" class="submit-summary" action="/api/upload/uploadFile/11" accept=".xls, .xlsx"
            :on-preview="handlePreview" :on-success="handleSuccess" :on-exceed="exceedFile"
            :before-upload="beforeUploadFile" :file-list="summaryList" :on-change="handleChange">
            <el-button type="primary" :class="authority.canSubmitSummarize ? 'mr-rh summary-btn green-btn' : ''"
              :disabled="!authority.canSubmitSummarize">项目负责人提交项目总结</el-button>
          </el-upload>
        </el-col>
      </el-row>
      <!-- 当前是符合条件的责任人并且文件上传修改的时候显示 -->
      <el-row v-if="authority.canSubmitSummarize && showSave">
        <el-button type="primary" size="small" @click="saveSummary(versionId)">保存</el-button>
      </el-row>
    </el-card>

    <TotalPlanDailog ref="totalPlanDailog" @submitForm="submitForm" />
    <VersionDialog ref="versionDialog" :projectId="projectId" :verOptions="verOptions" @updateTable="updateTable" />
    <NewTaskDailog ref="newTaskDailog" @submitTaskForm="submitTaskForm" :versionId="versionId" />
    <BugManageDialog ref="bugManageDialog" @refreshBug="refreshBug" />
  </div>
</template>

<script>
import ProjectProgress from "./component/projectProgress";
import ProgressTable from "./component/progressTable";
import TotalPlanDailog from "./component/totalPlanDailog";
import VersionDialog from "./component/versionDialog"; //版本管理弹框
import NewTaskDailog from "./component/newTaskDailog";
import BugManageDialog from "./component/bugManageDialog";
import {
  getVersionAuthority,
  getVersionList,
  getVerPlanList,
  getVerTaskPortList,
  getPortStatistical,
  getVersionBugInfo,
  addVersionPlan,
  modifyVersionPlan,
  addVerTaskPort,
  modifyVerTaskPort,
  submitVerSummary,
  getWebPrincipalList,
  getprjVersionBugInfo,
} from "@/service/progressApi";

import bus from "@/components/bus";
import { Login } from "../../../service/Api";

export default {
  name: "progressManager",
  components: {
    ProjectProgress,
    ProgressTable,
    TotalPlanDailog,
    VersionDialog,
    NewTaskDailog,
    BugManageDialog,
  },
  data() {
    return {
      headers: {
        "API-User-Token": sessionStorage.getItem("token"), //文件上传需携带token
      },
      functionDisabled: false, //功能列表默认不禁用
      projectName: this.$route.query.projectName,
      pn: this.$route.query.pn,
      //当前角色在进度管理下的权限
      authority: {
        canOperateVersion: true,
        canOperatePlan: true,
        canOperateTaskPort: true,
        canInternalTest: true,
        canClientTest: true,
        canSubmitBugs: true,
        canSubmitSummarize: true,
      },
      projectId: "",
      versionId: "",
      verOptions: [],
      showSave: false, //文件上传保存的按钮，默认不展示
      summaryList: [
        {
          name: "",
          url: "",
          status: "",
          uid: "",
        },
      ], //项目总结文件存储地址
      circleProgress: {
        flag: "circleProgress",
        data: [],
      },
      bugNumlist: [], //bug数量
      interfaceManagerList: [], //界面负责人
      lineProgress: {
        flag: "lineProgress",
        data: [],
      },
      summaryFile: {},
      totalPlanSetting: {
        data: [],
        column: [
          {
            prop: "stageName",
            label: "阶段",
            width: "300",
          },
          {
            prop: "workHours",
            label: "工期（天）",
            width: "150",
          },
          {
            prop: "startDate",
            label: "计划开始日期",
            width: "200",
          },
          {
            prop: "endDate",
            label: "计划结束日期",
            width: "200",
          },
          {
            prop: "target",
            label: "目标",
            width: "450",
          },
          {
            prop: "principalName",
            label: "责任人",
            width: "250",
          },
        ],
      },
    };
  },
  watch: {
    "lineProgress.data": function (newVal) {
      this.lineProgress.data = newVal;
      // this.$store.commit("SET_lineProgressData", newVal);
      // console.log(this.$store.state.lineProgressData);

      // if (this.lineProgress.data.length > 0) {
      //   this.functionDisabled = false;
      // } else {
      //   this.$message.info("请先添加任务端");
      //   this.functionDisabled = true;
      // }
    },
    deep: true,
    immediate: false,
  },
  created() {
    this.projectId = this.$route.query.projectId;
    this.versionListData(this.projectId);
    this.prjVersionBugInfo();
    if (this.summaryList[0].name === "" || this.summaryList[0].url === "") {
      this.summaryList = [];
    }
  },
  methods: {
    //获取版本列表
    versionListData(prjId) {
      getVersionList(prjId).then((res) => {
        if (res.data.length > 0) {
          this.verOptions = res.data;
          if (this.$route.query.versionId) {
            this.versionId = this.$route.query.versionId;
          } else {
            this.versionId = this.verOptions[0].id;
          }
          this.init(this.versionId);
          this.getSummaryList(this.versionId);
        } else {
          this.verOptions = []
          this.$message("抱歉，暂无数据！");
        }
      });
    },
    //选择版本
    changeVersion(versionId) {
      this.versionId = versionId;
      this.showSave = false; //切换版本的时候 让保存按钮默认不显示
      this.init(this.versionId);
      this.getSummaryList(versionId);
    },
    //将根据版本id获取到项目负责人项目总结文件的方法封装起来
    getSummaryList(vId) {
      let index = null;
      index = this.verOptions.findIndex((x) => x.id === vId);
      if (
        this.verOptions[index].verSummarize &&
        this.verOptions[index].verSummarizePath
      ) {
        let obj = {
          name: "",
          url: "",
        };
        obj.name = this.verOptions[index].verSummarize;
        obj.url = this.verOptions[index].verSummarizePath;
        this.summaryList[0] = Object.assign({}, obj);
        this.summaryList = [...this.summaryList];
      } else {
        this.summaryList = [];
      }
    },
    //获取当前项目进度管理下的权限
    verProgressAuthorityData(prjId, versionId) {
      getVersionAuthority(prjId, versionId).then((res) => {
        this.authority = res.data;
      });
    },
    init(verId) {
      //获取整体计划列表
      getVerPlanList(verId).then((res) => {
        this.totalPlanSetting.data = res.data;
      });
      //获取版本任务端列表
      getVerTaskPortList(verId).then((res) => {
        // ;
        this.lineProgress.data = res.data;
      });
      //获取所有任务端界面完成情况
      getPortStatistical(verId).then((res) => {
        this.circleProgress.data = res.data;
      });
      //获取版本开发人员的bug数与bug率
      getVersionBugInfo(verId).then((res) => {
        // ;
        this.bugNumlist = res.data;
      });
      // 获取当前项目当前版本进度管理下的权限
      this.verProgressAuthorityData(this.projectId, this.versionId);
    },
    //获取界面负责人下拉列表
    getWebPrincipalData() {
      getWebPrincipalList(this.versionId).then((res) => {
        this.interfaceManagerList = res.data;
      });
    },
    // 根据版本id查询此版本开发人员的bug数与bug率
    prjVersionBugInfo() {
      //   getprjVersionBugInfo(this.versionId).then(res => {
      //     ;
      //   });
    },
    // 版本管理刷新页面
    updateTable() {
      this.versionListData(this.projectId);
    },
    // 刷新整体计划
    verPlanListData() {
      getVerPlanList(this.versionId).then((res) => {
        this.totalPlanSetting.data = res.data;
      });
    },
    // 刷新任务端管理
    updateTaskPort() {
      getVerTaskPortList(this.versionId).then((res) => {
        this.lineProgress.data = res.data;
      });
      getPortStatistical(this.versionId).then((res) => {
        this.circleProgress.data = res.data;
      });
    },
    //刷新bug数
    refreshBug() {
      getVersionBugInfo(this.versionId).then((res) => {
        this.bugNumlist = res.data;
      });
    },
    //版本管理弹窗
    managerVersion() {
      this.$refs.versionDialog.dialogFormVisible = true;
    },
    //添加版本计划弹窗
    addPlan(title) {
      this.$refs.totalPlanDailog.showDailog(title);
    },
    //修改版本计划弹窗
    modifyPlan(title, row) {
      this.$refs.totalPlanDailog.showDailog(title, row);
    },
    //提交添加/修改的版本计划
    submitForm(formVal, title) {
      let obj = {};
      obj = Object.assign(obj, formVal);
      obj.principalId = formVal.principalId.join(",");
      this.$set(obj, "versionId", this.versionId);
      if (title == "添加计划") {
        // ;
        addVersionPlan({
          versionId: obj.versionId,
          stageId: obj.stageId,
          workHours: obj.workHours,
          startDate: obj.startDate,
          endDate: obj.endDate,
          principalId: obj.principalId,
          target: obj.target,
        }).then((res) => {
          if (res.code === 0) {
            this.$refs.totalPlanDailog.dialogFormVisible = false;
            this.$message.success("添加成功~");
            this.verPlanListData();
          } else {
            console.log("添加计划失败，查看原因", res.message);
          }
        });
      } else {
        //修改计划
        modifyVersionPlan(obj).then((res) => {
          if (res.code === 0) {
            this.$message.success("修改成功~");
            this.verPlanListData();
            this.$refs.totalPlanDailog.dialogFormVisible = false;
          } else {
            console.log("修改计划失败，查看原因", res.message);
          }
        });
      }
    },

    //新建任务端弹窗
    newTask(title) {
      if (!this.versionId) {
        this.$message.warning("请先选择版本");
        return;
      }
      this.getWebPrincipalData();
      this.$refs.newTaskDailog.showDailog(title);
    },
    //修改任务端弹窗
    modifyTask(title, item) {
      this.getWebPrincipalData();
      this.$refs.newTaskDailog.showDailog(title, item);
    },
    //提交新建/修改的任务端
    submitTaskForm(formVal, title) {
      let obj = {
        id: null,
        portName: "",
        pageUserId: "",
        isJava: null,
        verId: null,
      };
      obj.id = Number(formVal.id);
      obj.portName = formVal.portName + "端";
      //需要先判断界面负责人id是否为对象类型
      obj.pageUserId =
        typeof formVal.pageUserId === "object"
          ? formVal.pageUserId.join(",")
          : formVal.pageUserId;
      obj.isJava = Number(formVal.isJava);
      obj.verId = Number(this.versionId);
      if (title == "新增任务端") {
        addVerTaskPort({
          verId: obj.verId,
          portName: obj.portName,
          isJava: obj.isJava,
          pageUserId: obj.pageUserId,
        }).then((res) => {
          if (res.code === 0) {
            this.$refs.newTaskDailog.dialogFormVisible = false;
            this.$message.success("添加成功~");
            this.updateTaskPort();
          } else {
            // formVal.portName = "";
            // formVal.pageUserId = [];
            this.$message.info(res.message);
            this.$refs.newTaskDailog.dialogFormVisible = true;
          }
        });
      } else {
        //修改任务端
        modifyVerTaskPort(obj)
          .then((res) => {
            if (res.code === 0) {
              this.$message.success("修改成功~");
              this.$refs.newTaskDailog.dialogFormVisible = false;
              this.updateTaskPort();
            } else {
              // formVal.portName = formVal.portName.replace("端", "");
              // //需要先判断负责人id是否为字符串类型
              // if (typeof formVal.pageUserId === "string") {
              //   formVal.pageUserId = formVal.pageUserId
              //     .split(",")
              //     .map(elem => Number(elem));
              // }
              // console.log(formVal.pageUserId);

              this.$message.info(res.message);
              this.$refs.newTaskDailog.dialogFormVisible = true;
            }
          })

          .catch((rej) => {
            this.$message({
              type: "info",
              message: "修改失败",
            });
          });
      }
    },
    //进入功能列表
    managerFunctionList() {
      if (!this.versionId) {
        this.$message.warning("当前没有选择版本");
        return;
      }
      if (this.lineProgress.data.length <= 0) {
        this.$message.warning("当前暂无任务端数据");
        return;
      }
      this.$router.push({
        name: "progressManagerDetail",
        query: {
          versionId: this.versionId,
          projectName: this.projectName,
          projectId: this.projectId,
        },
      });
    },
    handleAddbug(row, title) {
      this.$refs.bugManageDialog.ruleForm = {
        testBugOne: "",
        testBugCount: "",
      };
      this.$refs.bugManageDialog.handleAddbug(row, title);
    },
    //当上传的项目总结文件更改的时候展示保存的按钮
    handleChange() {
      this.showSave = true;
    },
    //提交项目总结
    handleSuccess(res, file, fileList) {
      let obj = {
        name: "",
        url: "",
      };
      obj.name = file.name;
      obj.url = res.data.fileIds;
      this.summaryList[0] = Object.assign({}, obj);
      this.summaryList = [...this.summaryList];
      console.log(this.summaryList);
    },
    //保存更新之后的项目总结
    saveSummary(versionId) {
      let summaryFile = { id: "", verSummarize: "", verSummarizePath: "" };
      summaryFile.id = this.versionId;
      summaryFile.verSummarize = this.summaryList[0].name;
      summaryFile.verSummarizePath = this.summaryList[0].url;
      this.summaryFile = Object.assign({}, summaryFile);
      submitVerSummary(this.summaryFile).then((res) => {
        if (res.code == 0) {
          this.$message({
            type: "success",
            message: res.message,
            duration: 5000,
          });
          location.reload(); //强制页面刷新 待优化
        } else {
          this.$message.warning(res.message);
        }
      });
    },
    // 文件超出个数限制时的钩子
    exceedFile(files, fileList) {
      this.$message.warning({
        message: `只能选择 1 个文件，当前共选择了 ${files.length + fileList.length
          } 个`,
      });
    },
    // 上传文件之前的钩子
    beforeUploadFile(file) {
      let extension = file.name.substring(file.name.lastIndexOf(".") + 1);
      let size = file.size / 1024 / 1024;
      if (extension !== "xlsx" && extension !== "xls") {
        this.$message.warning({
          message: `只能上传后缀是.xls或.xlsx的文件`,
        });
      }
      if (size > 10) {
        this.$message.warning({
          message: `文件大小不得超过10M`,
        });
      }
    },
    //项目总结上传之后实现点击下载
    handlePreview(file) {
      var a = document.createElement("a");
      var event = new MouseEvent("click");
      a.download = file.name;
      a.href = file.url;
      a.dispatchEvent(event);
    },
  },
};
</script>

<style scoped>
@import "../../../styles/common.css";

.version-select {
  margin: 0 10px 0 30px;
}

.content-container .rh {
  margin: 0px;
}

.progress-manager-subtitle {
  font-size: 18px;
  font-family: Microsoft YaHei;
  font-weight: bold;
  color: rgba(48, 49, 51, 1);
  margin-bottom: 20px;
}

.version-table tr:first-child {
  background-color: #f9f9f9;
}

.new-add-btn {
  position: relative;
  top: -6px;
}

.green-btn {
  width: 120px;
  font-size: 14px;
  background-color: #00b98d;
  border-color: #00b98d;
}

.blue-btn {
  width: 120px;
  font-size: 14px;
  background-color: #409eff;
  border-color: #409eff;
}

.btn-wd {
  float: left;
}

.submit-summary {
  display: inline-block;
}

.summary-btn {
  width: 200px;
}
</style>